<template>
  <div class="box">
    <div @click="onStatus()" class="status">
      <svg
        v-if="!status.isRecord"
        t="1642938190332"
        class="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="2674"
        width="40"
        height="40"
      >
        <path
          d="M128 138.666667c0-47.232 33.322667-66.666667 74.176-43.562667l663.146667 374.954667c40.96 23.168 40.853333 60.8 0 83.882666L202.176 928.896C161.216 952.064 128 932.565333 128 885.333333v-746.666666z"
          fill="#ffffff"
          p-id="2675"
        ></path>
      </svg>
      <svg
        v-if="status.isRecord"
        t="1642938458345"
        class="icon"
        viewBox="0 0 1024 1024"
        version="1.1"
        xmlns="http://www.w3.org/2000/svg"
        p-id="3541"
        width="40"
        height="40"
      >
        <path
          d="M426.666667 138.666667v746.666666a53.393333 53.393333 0 0 1-53.333334 53.333334H266.666667a53.393333 53.393333 0 0 1-53.333334-53.333334V138.666667a53.393333 53.393333 0 0 1 53.333334-53.333334h106.666666a53.393333 53.393333 0 0 1 53.333334 53.333334z m330.666666-53.333334H650.666667a53.393333 53.393333 0 0 0-53.333334 53.333334v746.666666a53.393333 53.393333 0 0 0 53.333334 53.333334h106.666666a53.393333 53.393333 0 0 0 53.333334-53.333334V138.666667a53.393333 53.393333 0 0 0-53.333334-53.333334z"
          fill="#ffffff"
          p-id="3542"
        ></path>
      </svg>
    </div>
    <div class="record-list">
      <div :class="{'item-selected': item.selected}" v-for="(item, index) in allData" :key="item.name" class="item">
        <span @click="onPlay(allData[index])">{{ allData[index].name }}</span>
        <span @click="onExport(allData[index])"><img class="icon-export" src="/src/assets/images/export.png" alt=""></span>
        <span @click="onDeleteRecordItem(index)" class="icon-delete font-gray-blue-color plr10"></span>
      </div>
    </div>
  </div>
</template>

<script>
import common from "@/assets/js/common";
export default {
  components: {},
  props: {
    initAllData: {
      type: Array,
      default: [],
    },
  },
  data() {
    return {
      status: {
        isRecord: false, // 是否记录
        isPlay: false 
      },
      intervalTemp: {
        isStart: false,  // 是否停止定时器
        lastDivTime: 0,
        curIndex: 0,
        dataLength: 0,
        data: []
      }, // 定时器
      // interval: 0, // 当前的定时器id
      // currentTime: 0, // 当前时间
      startTime: 0, // 开始时间
      data: [], // 记录的数据
      allData: [], // 所有的记录数据
    };
  },
  created() {
    this.initData();
  },
  methods: {
    initData() {
      this.allData = this.initAllData ?? [];
      this.status.isPlay = false;
      this.intervalTemp = {
        func: null,
        curTime: 0,
        curIndex: 0,
        maxIndex: 0,
        data: []
      };
      this.clearRecordCache();
    },
    clearRecordCache() {
      this.status.isRecord = false;
      this.startTime = 0;
      this.data = [];
    },
    // 添加一条记录
    addData(item) {
      if (!this.status.isRecord) {
        return;
      }
      this.data.push({
        time: this.getTime(),
        data: item,
      });
    },
    // 开始记录
    start() {
      this.status.isRecord = true;
      this.startTime = this.getTime();
      // this.interval = setInterval(() => {
      //   this.currentTime++;
      //   console.log(this.currentTime);
      // }, 1);
      console.log("开始记录");
    },
    // 结束记录
    close() {
      // clearInterval(this.interval);
      let data = this.dealWithData(this.data);
      if(data){
        this.allData.push(data);
      }
      this.clearRecordCache();
      this.onUpdateRecord();
      console.log("结束记录");
    },
    // 开始or结束状态
    onStatus() {
      this.status.isRecord = !this.status.isRecord;
      this.status.isRecord ? this.start() : this.close();
    },
    // 录音数据整理
    dealWithData(data) {
      if (data.length == 0) {
        return null;
      }
      let result = {
        name: "",
        data: [],
        selected: false
      };
      let minTime = data[0].time;
      let itemTemp = {};
      let priorTime = 0, curTime = 0;
      result.name = "record_" + common._dateFormat(minTime);
      for (let i = 0; i < data.length; i++) {
        itemTemp = data[i];
        curTime = itemTemp.time - minTime;
        result.data.push({
          id: itemTemp.data.id,
          time: curTime,
          highNum: itemTemp.data.highNum,
          file: itemTemp.data.audio.srcM,
          divTime: curTime - priorTime,
          num: itemTemp.data.num
        });
        priorTime = curTime;
      }
      return result;
    },
    // 获取时间
    getTime(firstTime = "", operation = "none", secondTime = "") {
      let date = null;
      switch (operation) {
        case "none":
          date = firstTime
            ? new Date(firstTime).getTime()
            : new Date().getTime();
          break;
        case "+":
          if (!firstTime) {
            date = new Date().getTime();
            break;
          }
          if (secondTime) {
            date =
              new Date(firstTime).getTime() + new Date(secondTime).getTime();
          } else {
            date = new Date(firstTime).getTime() + new Date().getTime();
          }
          break;
        case "-":
          if (!firstTime) {
            date = new Date().getTime();
            break;
          }
          if (secondTime) {
            date =
              new Date(firstTime).getTime() - new Date(secondTime).getTime();
          } else {
            date = new Date().getTime();
            let date2 = new Date(firstTime).getTime();
            date = date > date2 ? date - date2 : date2 - date;
          }
          break;
      }
      return date;
    },
    // 更新所有记录数据事件
    onUpdateRecord() {
      this.$emit("onUpdateRecord", this.allData);
    },
    // 播放记录
    onPlay(item){
      this.status.isPlay = !this.status.isPlay;
      if(this.status.isPlay){
        this.intervalTemp = {
          isStart: true,
          lastDivTime: 0,
          curIndex: 0,
          dataLength: item.data.length,
          data: item.data
        }
        this.allData = this.allData.map((item) => {
          item.selected = false;
          return item;
        });
        item.selected = true;
        this.startPlay();
      }else{
        this.stopPlay();
      }
    },
    // 播放递归
    startPlay(){
      let that = this;
      setTimeout(() => {
        if(!that.intervalTemp.isStart || that.intervalTemp.curIndex >= that.intervalTemp.dataLength){
          that.stopPlay();
          return;
        }
        that.onPlayRecord(that.intervalTemp.data[that.intervalTemp.curIndex]);
        that.intervalTemp.curIndex += 1;
        if(that.intervalTemp.data[that.intervalTemp.curIndex]){
          that.intervalTemp.lastDivTime = that.intervalTemp.data[that.intervalTemp.curIndex].divTime;
        }
        that.startPlay();
      }, this.intervalTemp.lastDivTime);
    },
    // 停止播放
    stopPlay(){
      this.status.isPlay = false;
      this.allData = this.allData.map((item) => {
        item.selected = false;
        return item;
      });
      this.intervalTemp = {
        isStart: true,
        lastDivTime: 0,
        curIndex: 0,
        dataLength: 0,
        data: []
      };
    },
    // 播放单个音
    onPlayRecord(item){
      this.$emit("onPlayRecord", item);
    },
    // 导出乐谱
    onExport(data){
      this.toGo('export', data);
    },
    // 删除更新记录
    onDeleteRecordItem(index){
      this.allData.splice(index, 1);
      this.onUpdateRecord();
    },
    toGo(url, params = {}){
      if(this.status.isRecord){
        this.close();
      }
      if(this.status.isPlay){
        this.stopPlay();
      }
      this.$router.push({
        name: url,
        params: {
          data: JSON.stringify(params)
        }
      });
    }
  }
};
</script>

<style scoped>
.status {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  opacity: 0.8;
}

.box,
.record-list {
  width: 100%;
}

.record-list > .item {
  width: 100%;
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
  margin-bottom: 8px;
  border-bottom: 1px solid gray;
}

.record-list > .item-selected{
  color: rgb(70, 118, 163);
}

.icon-export {
  width: 18px;
  height: 18px;
}

.icon-delete {
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
}
</style>